<?php

namespace App\Http\Middleware\OpenShop;

use App\Library\Common\JwtTool;
use App\Library\Rms\RmsShopApi;
use App\Service\OpenShop\Merchant\MerchantAuth;
use App\Service\OpenShop\User\RmsUserService;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class MerchantAppAuth
{
    public static $userId = 0;

    /**
     * 验证商家APP是否登录
     * @param Request $request
     * @param Closure $next
     * @return JsonResponse|mixed
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle(Request $request, Closure $next)
    {
        $shopId  = (int)$request->header('shopId');
        $brandId = (int)$request->header('brandId');
        $jwt     = (string)$request->header('authorization');

        if (config('app.env') == 'dev' && !$jwt) {
            self::$userId                   = 6;
            $userInfo                       = (object)['id' => self::$userId];
            app()->get('request')->userInfo = (object)['id' => self::$userId];
            $request->setUserResolver(function () use ($userInfo) {
                return (object)$userInfo;
            });
            return $next($request);
        }

        // 简单解析jwt - 数据未校验
        $payload        = JwtTool::getJwtPayload($jwt);
        $thirdLoginType = $payload['thirdLoginType'] ?? '';

        app()->get('request')->loginType = $thirdLoginType;
//        $userId         = $payload['sub'] ?? 0;

        // TODO
//        if ($thirdLoginType == 'fs') {
//
//            // 飞书登录，走现有逻辑
//            $userInfo = MerchantAuth::userinfoWithShopAuth();
//        } else {
//
//            // 普通登录，走缓存逻辑 - 量大
//            // TODO 大缓存
//            $cacheKey = "MerchantAppAuth_common:" . md5($jwt . '-' . $brandId);
//            $userInfo = Cache::remember($cacheKey, 60, function () use ($jwt, $brandId) {
//                return (new RmsShopApi())->getUserinfoWithShopAuth($jwt, $brandId, 0)['data'] ?? null;
//            });
//        }

        // 飞书登录，走现有逻辑
        $userInfo = MerchantAuth::userinfoWithShopAuth($jwt, $brandId, $shopId);

        if (null === $userInfo) {
            return response()->json([
                'code' => 401,
                'msg'  => '尚未登录或者登录凭证失效',
            ]);
        }

        self::$userId                   = $userInfo['id'] ?? 0;
        app()->get('request')->userInfo = (object)['id'       => self::$userId,
                                                   'username' => $userInfo['username'],
                                                   'mobile'   => $userInfo['mobile']
        ];

        $request->setUserResolver(function () use ($userInfo) {
            return (object)$userInfo;
        });


        // 选品建议飞书端
        $headerPlatformName = $request->header('platformName', '');
        if ($shopId == -1 || ($headerPlatformName == UserPermissionAuth::MODULE_PRODUCT_SELECTION_PROPOSAL && $shopId == 0)) {// 选品建议飞书端未选择店铺
            return $next($request);
        }

        $shopLists = $userInfo['shopLists'] ?? [];

        if (in_array($shopId, array_column($shopLists, 'id'))) {
            return $next($request);
        }

        return response()->json([
            'code' => 403,
            'msg'  => '无权限操作此店铺',
        ]);
    }
}
